package com.ndp.fb.walle.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.DBObject;
import com.ndp.fb.exception.CheckedException;
import com.ndp.fb.mongo.api.EcMarketingActionRecordMongoService;
import com.ndp.fb.util.DateUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Created by jacky.cheng on 2016/6/8.
 */
@RestController
@RequestMapping("/action/marketing")
public class EcMarketingActionRecordController {

    @Reference
    EcMarketingActionRecordMongoService ecMarketingActionRecordMongoService;

    @RequestMapping("save")
    public Boolean save(JSONObject action) throws CheckedException {
        try {
            ecMarketingActionRecordMongoService.save(action);
        } catch (Exception e) {
            throw new CheckedException("insert mongo error!");
        }
        return true;
    }

    @RequestMapping("findByIdToday")
    public List<JSONObject> findByIdToday(Long id) {
        Date today = new Date();
        //查找今天一整天（凌晨到明天凌晨）的数据
        Iterator<DBObject> it = ecMarketingActionRecordMongoService.findByIdAndDate(id,
                DateUtil.getUtcDayZero(today),
                DateUtil.getUtcDayZero(DateUtil.addDateByTypeAndOffset(today, Calendar.DATE, 1)));
        return parseIt(it);
    }
    @RequestMapping("findByIdAndDate")
    public List<JSONObject> findByIdAndDate(Long id,Long startDate,Long endDate) {
        Iterator<DBObject> it = ecMarketingActionRecordMongoService.findByIdAndDate(id,
                new Date(startDate),
                new Date(endDate));
        return parseIt(it);
    }

    private List<JSONObject> parseIt(Iterator<DBObject> it){
        List<JSONObject> r = new ArrayList<>();
        while (it.hasNext()) {
            r.add((JSONObject) it.next());
        }
        return r;
    }
}
